package com.opencms.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.opencms.bean.User;
import com.opencms.controller.base.AdminBaseController;
import com.opencms.service.UserService;
import com.opencms.vo.ActionResult;
import com.opencms.vo.QueryResult;

@Controller
@RequestMapping("/admin/user/")
@SessionAttributes("pageForm")
public class UserController extends AdminBaseController{
	@Autowired
	private UserService userService;
	/**
	 * 列表
	 */
	@RequestMapping("list")
    public ModelAndView list(User user,HttpServletRequest request,ModelMap mode) throws Exception{
		
		QueryResult<User> queryResult=userService.list(user);
		user.setPageDate(queryResult.getQueryResult());
		user.setTotalCount(queryResult.getCount());
		
		ModelAndView mnv = new ModelAndView();
		mnv.addObject(DEFAULT_PAGE_VIEW,user);
		mnv.setViewName("view/admin/user/list");
		return mnv;
		
	}
    /**
     * 删除
     */
	@RequestMapping("delete")
	@ResponseBody
	public ActionResult delete(User user,HttpServletRequest request,ModelMap mode) throws Exception{
		ActionResult result=new ActionResult();
		try {
			userService.deleteByPrimaryKey(user.getId());
			result.setSuccess(true);
			result.setMessage(RESULE_SUCCESS_DELETE);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR_DELETE);
		}
		return result;
	}
	 /**
     * 添加或修改表单
     */
	@RequestMapping("showForm")
	public ModelAndView addForm(User user,HttpServletRequest request) throws Exception{
		ModelAndView mnv = new ModelAndView();
		if(user.getId()!=null){
			user=userService.selectByPrimaryKey(user.getId());
		}
		mnv.addObject(DEFAULT_PAGE_FORM, user);
		mnv.setViewName("view/admin/user/form");
		return mnv;
		
	}
	/**
	 * 添加或修改
	 */
	@RequestMapping("addOrUpdate")
	@ResponseBody
	public ActionResult add(User user,HttpServletRequest request) throws Exception{
		ActionResult result=new ActionResult();
		try {
			userService.saveOrUpdate(user);
			result.setSuccess(true);
			result.setMessage(RESULE_SUCCESS);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR);
		}
		return result;
	}

}
